package es.osoco.basicpomodoro;

import es.osoco.basicpomodoro.preferences.PomodoroPreferences;
import es.osoco.basicpomodoro.timer.PomodoroService;
//import es.osoco.basicpomodoro.time.PomodoroService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
	private long time = 1;
	private PomodoroService service;
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			service = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			Log.d("CONNECTION", "OK");
			service = ((PomodoroService.ServiceBinder)binder).getService();	
		}
	};
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Context context = getApplicationContext();
		Intent intent = new Intent(context, PomodoroService.class);
		bindService(intent, connection, Context.BIND_AUTO_CREATE);
		
		Button button1 = (Button) findViewById(R.id.startButton);
		button1.setOnClickListener(new OnClickListener() {		
			
			@Override
			public void onClick(View v) {
				service.startPomodoro(time);
			}
		});
		
		Button button2 = (Button) findViewById(R.id.addTimeButton);
		button2.setOnClickListener(new OnClickListener() {		
			
			@Override
			public void onClick(View v) {
				Context context = getApplicationContext();
				Intent intent = new Intent(context,AddDuration.class);
				startActivityForResult(intent, 1);
			}
		});
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	switch(requestCode) {
    		case 1: {
    			if(resultCode == Activity.RESULT_OK) {
    				time = data.getLongExtra("TIME", 1);
    			}
    		}
    	}
    }
    
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        	
    	menu.add(0,Menu.FIRST, Menu.NONE, R.string.settings);
	    
	    return	true ;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	super.onOptionsItemSelected(item);
    	
    	boolean toReturn = false;
    	
    	switch(item.getItemId()) {
    		case Menu.FIRST: {
    			Context context = getApplicationContext();
    			Intent intent = new Intent(context, PomodoroPreferences.class);
    			startActivity(intent);
    			toReturn = true;
    		}
    	}
    	
		return toReturn;
    }
}